<template>
    <div class="post-main">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>帖子列表</span>
                    <el-button type="primary" size="small" @click="handlePublish">发布新帖子</el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-input v-model="searchValue" placeholder="搜索帖子" class="search-input" clearable
                    @keyup.enter="handleSearch">
                    <template #append>
                        <el-button icon="Search" @click="handleSearch"></el-button>
                    </template>
                </el-input>

                <el-select v-model="categoryValue" placeholder="选择分类" clearable @change="handleCategoryChange">
                    <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

                <el-select v-model="sortValue" placeholder="排序方式" @change="handleSortChange">
                    <el-option v-for="item in sortOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>

            <!-- 帖子列表 -->
            <div class="post-list" v-loading="loading">
                <el-empty description="暂无帖子" v-if="posts.length === 0 && !loading" />

                <div v-for="post in posts" :key="post.id" class="post-item">
                    <el-card shadow="hover">
                        <div class="post-header">
                            <div class="user-info">
                                <el-avatar :size="40" :src="post.avatar || defaultAvatar"></el-avatar>
                                <span class="username">{{ post.username || post.nickname || '未知用户' }}</span>
                            </div>
                            <span class="post-time">发布于：{{ formatTime(post.createdAt) }}</span>
                        </div>

                        <div class="post-title" @click="viewPostDetail(post.id)">{{ post.title }}</div>
                        <div class="post-content">{{ post.content }}</div>

                        <div class="post-footer">
                            <div class="post-tags">
                                <el-tag v-if="post.category" size="small">{{ getCategoryLabel(post.category) }}</el-tag>
                            </div>
                            <div class="post-stats">
                                <span><el-icon><View /></el-icon>  {{ post.viewCount || 0 }}</span>
                                <span><el-icon><ChatDotRound /></el-icon> {{ post.commentCount || 0 }}</span>
                                <span><el-icon><StarFilled /></el-icon> {{ post.likeCount || 0 }}</span>
                            </div>
                        </div>
                    </el-card>
                </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
// import { formatDistanceToNow } from 'date-fns';
import { View, ChatDotRound, StarFilled } from "@element-plus/icons-vue";
import postsApi, { type Post, type PostsQueryParams } from '@/api/posts';

const router = useRouter();
const loading = ref(false);
const posts = ref<Post[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchValue = ref('');
const categoryValue = ref('');
const sortValue = ref('newest');
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

const categories = [
    { value: 'apartment', label: '公寓信息' },
    { value: 'roommate', label: '室友寻找' },
    { value: 'experience', label: '居住体验' },
    { value: 'question', label: '问题咨询' },
    { value: 'other', label: '其他' },
];

const sortOptions = [
    { value: 'newest', label: '最新发布' },
    { value: 'hottest', label: '最热门' },
    { value: 'mostComments', label: '评论最多' },
];

// 获取帖子列表
const fetchPosts = async () => {
    loading.value = true;
    try {
        const params: PostsQueryParams = {
            visible: true
        };
        
        // 添加分类筛选
        if (categoryValue.value) {
            params.category = categoryValue.value;
        }
        
        console.log('Fetching posts with params:', params);
        
        // 获取帖子列表
        const data = await postsApi.getPosts(params);
        console.log('Fetched posts:', data);
        posts.value = data;
        total.value = data.length;
        
        loading.value = false;
    } catch (error) {
        console.error('Error fetching posts:', error);
        ElMessage.error('获取帖子列表失败');
        loading.value = false;
    }
};

// 获取分类标签
const getCategoryLabel = (categoryValue: string): string => {
    const category = categories.find(c => c.value === categoryValue);
    return category ? category.label : '其他';
};

// 格式化时间
const formatTime = (time: Date | string | undefined): string => {
    if (!time) return '';
    
    const date = new Date(time);
    
    // Format: YYYY-MM-DD HH:MM:SS
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理搜索
const handleSearch = () => {
    currentPage.value = 1;
    fetchPosts();
};

// 处理分类变化
const handleCategoryChange = () => {
    currentPage.value = 1;
    fetchPosts();
};

// 处理排序变化
const handleSortChange = () => {
    currentPage.value = 1;
    fetchPosts();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    fetchPosts();
};

// 处理每页数量变化
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
    fetchPosts();
};

// 查看帖子详情
const viewPostDetail = (id: string) => {
    router.push({ 
        path: '/posts/detail',
        query: { pid: id }
    });
};

// 发布新帖子
const handlePublish = () => {
    router.push({ path: '/posts/publish' });
};

onMounted(() => {
    fetchPosts();
});
</script>

<style scoped>
.post-main {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-area {
    display: flex;
    margin-bottom: 20px;
    gap: 10px;
}

.search-input {
    flex: 1;
}

.post-list {
    margin-bottom: 20px;
}

.post-item {
    margin-bottom: 15px;
}

.post-item .el-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.post-item .el-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.post-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.username {
    font-weight: bold;
}

.post-time {
    color: #909399;
    font-size: 14px;
}

.post-title {
    font-size: 18px;
    font-weight: bold;
    margin: 10px 0;
    cursor: pointer;
    color: #409EFF;
}

.post-title:hover {
    text-decoration: underline;
}

.post-content {
    color: #606266;
    margin-bottom: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.post-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
}

.post-stats {
    display: flex;
    gap: 15px;
    color: #909399;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>
